Running Bash commands in Python - Stack Overflow

Some summary:

  1. Use subprocess.run()
  2. Be aware of the following argument possibilities with subprocess.run():
    • check=True — Raises an error should the process fails
    • stdout=subprocess.PIPE and stderr=subprocess.PIPE to capture outputs from process
    • universal_newlines=True (or text=True in Python 3.7) — Ensures that stdout and stderr are encoded as unicode instead of byte strings
    • shell=True
      • Pass a single string to your shell
      • Able to take advantage of shell features like redirection, wildcard expansions, etc
    • shell=False
      • (Default) Supply arguments as a list. Augment shlex.split to return appropriate list from a string.
      • More lightweight, reduces hidden complexities and minimizes chance of bugs and security problems
      • Limitations of not using shell can be handled directly via Python
    • env={‘foo’: ‘bar’} — Exposes environmental variable foo with value ”bar” to subprocess
    • executable:/bin/bash — Specify which executable should execute this process